package com.tempjob.app.controller;

import com.anwen.mongo.conditions.query.LambdaQueryChainWrapper;
import com.anwen.mongo.conditions.query.QueryWrapper;
import com.anwen.mongo.conditions.update.UpdateWrapper;
import com.anwen.mongo.model.PageParam;
import com.anwen.mongo.model.PageResult;
import com.tempjob.app.dto.*;
import com.tempjob.app.security.annotation.UserLogAnnotation;
import com.tempjob.app.security.annotation.UserPassportSSO;
import com.tempjob.app.service.TokenService;
import com.tempjob.app.vo.*;
import com.tempjob.common.businesss.mongo.entity.*;
import com.tempjob.common.businesss.service.MongoBeanUtil;
import com.tempjob.common.context.UserContext;
import com.tempjob.common.context.UserContextManage;
import com.tempjob.common.exception.BusinessException;
import com.tempjob.common.model.BaseSearchPageDTO;
import com.tempjob.common.model.WorkDayModel;
import com.tempjob.common.utils.CachedBeanCopier;
import com.tempjob.common.utils.DateUtilsEx;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/job")
@UserPassportSSO
@Api(tags = "工作信息")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class JobController {

    @Autowired
    private MongoBeanUtil mongoBeanUtil;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(response = CompanyInfo.class, value = "更新企业信息", notes = "")
    @PostMapping(value = "/updateCompanyInfo")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "更新工作信息")
    public Object updateCompanyInfo(@RequestBody ModifyCompanyInfoDTO dto) {
        UserInfo user = mongoBeanUtil.getUserInfoService().getById(UserContextManage.getContext().getId());
        CompanyInfo companyInfo = mongoBeanUtil.getCompanyInfoService().one(new QueryWrapper<CompanyInfo>().eq(CompanyInfo::getUserId, user.getId()));
        if (companyInfo == null || !companyInfo.getUserId().equals(user.getId())) {
            throw new BusinessException("未找到该记录");
        }
        if (companyInfo.getCompanyStatus() != null && companyInfo.getCompanyStatus() == 2) {
            throw new BusinessException("被禁用，请联系管理员");
        }
        companyInfo.setUserId(user.getId());
        companyInfo.setCompanyStatus(1);
        if (StringUtils.isNotBlank(dto.getIndustryCategory())) {
            IndustryCategory category = mongoBeanUtil.getIndustryCategoryService().getById(dto.getIndustryCategory());
            if (category != null) {
                companyInfo.setIndustryCategory(dto.getIndustryCategory());
                companyInfo.setIndustryCategoryName(category.getCategoryName());
            }
        }
        companyInfo.setCompanyNature(dto.getCompanyNature());
        companyInfo.setCompanyWelfare(dto.getCompanyWelfare());
        companyInfo.setCompanyLogo(StringUtils.isNotBlank(dto.getCompanyLogo()) ? dto.getCompanyLogo() : companyInfo.getCompanyLogo());
        companyInfo.setCompanyScale(dto.getCompanyScale() == null ? companyInfo.getCompanyScale() : dto.getCompanyScale());
        companyInfo.setCompanyDesc(StringUtils.isNotBlank(dto.getCompanyDesc()) ? dto.getCompanyDesc() : companyInfo.getCompanyDesc());
        companyInfo.setDescImages(dto.getDescImages() == null ? companyInfo.getDescImages() : dto.getDescImages());
        companyInfo.setIco(StringUtils.isNotBlank(dto.getIco()) ? dto.getIco() : companyInfo.getIco());
        companyInfo.setLongitude(dto.getLongitude() == null ? companyInfo.getLongitude() : dto.getLongitude());
        companyInfo.setLatitude(dto.getLatitude() == null ? companyInfo.getLatitude() : dto.getLatitude());
        companyInfo.setCompanyAddress(StringUtils.isNotBlank(dto.getCompanyAddress()) ? dto.getCompanyAddress() : companyInfo.getCompanyAddress());
        mongoBeanUtil.getCompanyInfoService().saveOrUpdate(companyInfo);
        user.setCompanyId(companyInfo.getId());
        if (user.getUserType() == null || !user.getUserType().contains(2)) {
            if (user.getUserType() == null) {
                user.setUserType(Arrays.asList(2));
            } else {
                user.getUserType().add(2);
            }
        }
        mongoBeanUtil.getUserInfoService().updateById(user);
        UserContext userContext = tokenService.getUserContext(user.getId());
        tokenService.createTicket(userContext, UserContextManage.getAuthorization());
        UserContextManage.reInit(userContext, UserContextManage.getAuthorization());
        return companyInfo;
    }

    @ApiOperation(response = JobInfoDetailVO.class, value = "工作详情", notes = "")
    @PostMapping(value = "/jobDetail")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "工作详情")
    @UserPassportSSO(ignore = true, needInfo = true)
    public Object jobDetail(@RequestBody IdQueryDTO dto) {
        JobInfo job = mongoBeanUtil.getJobInfoService().getById(dto.getId());
        JobInfoDetailVO detail = new JobInfoDetailVO();
        CachedBeanCopier.copyObject(job, detail);
        if (StringUtils.isNotBlank(job.getCompanyId())) {
            CompanyInfo company = mongoBeanUtil.getCompanyInfoService().getById(job.getCompanyId());
            detail.setCompanyInfo(company);
            if (company != null) {
                detail.setCompanyNature(company.getCompanyNature());
                detail.setCompanyScale(company.getCompanyScale());
                detail.setCompanyWelfare(company.getCompanyWelfare());
            }
        }
        detail.setApplyStaus(0);
        if (UserContextManage.getContext() != null) {
            JobApplyRecord apply = mongoBeanUtil.getJobApplyRecordService().lambdaQuery().eq(JobApplyRecord::getJobId, job.getId())
                    .ne(JobApplyRecord::getApplyStatus, 4).eq(JobApplyRecord::getUserId, UserContextManage.getContext().getId()).one();
            detail.setApplyStaus(apply != null ? apply.getApplyStatus() : 0);
        }
        if (job.getJobType().equals(1)) {
            List<WorkDayModel> workDayList = job.getTempJobInfo().getWorkDayHireList();
            List<WorkDayModel> listDay = workDayList.stream().sorted(Comparator.comparing(WorkDayModel::getDay)).collect(Collectors.toList());
            if (UserContextManage.getContext() != null) {
                Date currentDate = DateUtilsEx.getDayStart(new Date());
                String currentDay = DateUtilsEx.getDay(currentDate);
                List<UserTempJobRecord> tempUserApplys = mongoBeanUtil.getUserTempJobRecordService().lambdaQuery().eq(UserTempJobRecord::getJobId, job.getId())
                        .ne(UserTempJobRecord::getApplyStatus, 4).eq(UserTempJobRecord::getUserId, UserContextManage.getContext().getId()).list();
                for (WorkDayModel workDayModel : listDay) {
                    Date workDay = DateUtilsEx.getDayStart(DateUtilsEx.parseDayByDay(workDayModel.getDay()));
                    if (currentDate.compareTo(workDay) <= 0 || currentDay.equals(workDayModel.getDay())) {
                        UserTempJobRecord applyed = tempUserApplys.stream().filter(i -> i.getWorkDate().equals(workDayModel.getDay())).findFirst().orElse(null);
                        workDayModel.setApplyStatus(applyed == null ? 0 : applyed.getApplyStatus());
                    }
                }
            }
            detail.getTempJobInfo().setWorkDayHireList(listDay);
        }
        if (StringUtils.isNotBlank(job.getJobCategory())) {
            JobCategory category = mongoBeanUtil.getJobCategoryService().getById(job.getJobCategory());
            detail.setJobCategoryName(category.getCategoryName());
        }
        detail.setWorkOnTime(DateUtilsEx.getStringHDateTime(job.getWorkOnTime()));
        detail.setWorkOffTime(DateUtilsEx.getStringHDateTime(job.getWorkOffTime()));
        detail.setDeadline(DateUtilsEx.getDay(job.getDeadline()));
        if (UserContextManage.getContext() != null) {
            UserJobBrowseRecord record = mongoBeanUtil.getUserJobBrowseRecordService().lambdaQuery().eq(UserJobBrowseRecord::getUserId, UserContextManage.getContext().getId()).eq(UserJobBrowseRecord::getJobId, job.getId()).one();
            if (record == null) {
                record = new UserJobBrowseRecord();
                record.setJobId(job.getId());
                record.setUserId(UserContextManage.getContext().getId());
            }
            record.setJobCategory(job.getJobCategory());
            record.setJobTitle(job.getJobTitle());
            record.setJobType(job.getJobType());
            record.setExperience(job.getExperience());
            record.setEducation(job.getEducation());
            record.setSkill(job.getSkill());
            record.setOperTime(new Date());
            mongoBeanUtil.getUserJobBrowseRecordService().saveOrUpdate(record);
        }
        return detail;
    }

    @ApiOperation(response = Boolean.class, value = "工作申请", notes = "")
    @PostMapping(value = "/applyJob")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "工作申请")
    public Object applyjob(@RequestBody ApplyNormalJobDTO dto) {
        JobInfo job = mongoBeanUtil.getJobInfoService().getById(dto.getJobId());
        if (job == null || !job.getJobStatus().equals(1) || !job.getAuditStatus().equals(1)) {
            throw new BusinessException("工作不存在");
        }
        JobApplyRecord apply = mongoBeanUtil.getJobApplyRecordService().lambdaQuery().eq(JobApplyRecord::getJobId, job.getId()).eq(JobApplyRecord::getUserId, UserContextManage.getContext().getId()).one();
        if (apply == null) {
            apply = new JobApplyRecord();
        }
        if (!job.getJobType().equals(1) && apply != null && (apply.getApplyStatus().equals(2) || apply.getApplyStatus().equals(3))) {
            throw new BusinessException("不允许申请");
        }
        String id = apply.getId();
        CachedBeanCopier.copyObject(job, apply);
        apply.setId(id);
        apply.setJobId(job.getId());
        apply.setUserId(UserContextManage.getContext().getId());
        apply.setApplyStatus(1);
        apply.setApplyTime(new Date());
        apply.setWorkDates(dto.getWorkDates());
        if (job.getJobType().equals(1) && dto.getWorkDates() != null && !dto.getWorkDates().isEmpty()) {
            List<UserTempJobRecord> tempList = new ArrayList<>();
            List<UserTempJobRecord> userRecord = mongoBeanUtil.getUserTempJobRecordService().lambdaQuery().eq(UserTempJobRecord::getUserId, UserContextManage.getContext().getId()).ne(UserTempJobRecord::getApplyStatus, 4).in(UserTempJobRecord::getWorkDate, dto.getWorkDates()).list();
            for (String workDate : dto.getWorkDates()) {
                UserTempJobRecord record = new UserTempJobRecord();
                record.setJobId(job.getId());
                record.setJobType(job.getJobType());
                record.setUserId(UserContextManage.getContext().getId());
                record.setWorkDate(workDate);
                record.setApplyStatus(1);
                record.setWorkOnTime(job.getWorkOnTime());
                record.setWorkOffTime(job.getWorkOffTime());
                record.setApplyTime(new Date());
                //这里要检查时间是否有重叠
                List<UserTempJobRecord> userDayWorks = userRecord.stream().filter(userTempJobRecord -> userTempJobRecord.getWorkDate().equals(workDate)).collect(Collectors.toList());
                for (UserTempJobRecord userDayWork : userDayWorks) {
                    if (record.getDayWorkOnTime().before(userDayWork.getDayWorkOffTime()) || record.getDayWorkOffTime().before(userDayWork.getDayWorkOnTime())) {
                        throw new BusinessException("与已申请的工作时间冲突!");
                    }
                }
                tempList.add(record);
            }
            mongoBeanUtil.getUserTempJobRecordService().saveBatch(tempList);
        }
        mongoBeanUtil.getJobApplyRecordService().saveOrUpdate(apply);
        return true;
    }

    @ApiOperation(response = Boolean.class, value = "取消工作申请", notes = "")
    @PostMapping(value = "/cancelApplyJob")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "取消工作申请")
    public Object cancelApplyJob(@RequestBody IdQueryDTO dto) {
        JobApplyRecord apply = mongoBeanUtil.getJobApplyRecordService().getById(dto.getId());
        if (apply == null || !apply.getUserId().equals(UserContextManage.getContext().getId()) || apply.getJobType().equals(1)) {
            throw new BusinessException("记录错误");
        }
        JobInfo job = mongoBeanUtil.getJobInfoService().getById(apply.getJobId());
//        if (job != null && job.getJobStatus().equals(1) && apply.getWorkDates() != null && !apply.getWorkDates().isEmpty()) {
//            List<WorkDayModel> workDayModels = job.getTempJobInfo().getWorkDayHireList();
//            for (WorkDayModel workDayModel : workDayModels) {
//                if (apply.getWorkDates().contains(workDayModel.getDay())) {
//                    workDayModel.setWorkerNumRecruited(workDayModel.getWorkerNumRecruited() == null ? 0 : workDayModel.getWorkerNumRecruited() - 1);
//                }
//            }
//            mongoBeanUtil.getJobInfoService().updateById(job);
//        }
        apply.setApplyStatus(4);
        apply.setContactTime(new Date());
        return mongoBeanUtil.getJobApplyRecordService().updateById(apply);
    }

    @ApiOperation(response = Boolean.class, value = "取消零工申请", notes = "")
    @PostMapping(value = "/cancelTempApplyJob")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "取消零工工作申请")
    public Object cancelTempApplyJob(@RequestBody IdQueryDTO dto) {
        UserTempJobRecord apply = mongoBeanUtil.getUserTempJobRecordService().getById(dto.getId());
        if (apply == null || !apply.getUserId().equals(UserContextManage.getContext().getId())) {
            throw new BusinessException("记录错误");
        }
        if (apply.getApplyStatus().equals(3)) {
            throw new BusinessException("工作已确认，不能取消!");
        }
        JobInfo job = mongoBeanUtil.getJobInfoService().getById(apply.getJobId());
        if (job != null && job.getJobStatus().equals(1) && StringUtils.isNotBlank(apply.getWorkDate())) {
            List<WorkDayModel> workDayModels = job.getTempJobInfo().getWorkDayHireList();
            for (WorkDayModel workDayModel : workDayModels) {
                if (apply.getWorkDate().equals(workDayModel.getDay())) {
                    workDayModel.setWorkerNumRecruited(workDayModel.getWorkerNumRecruited() == null ? 0 : workDayModel.getWorkerNumRecruited() - 1);
                }
            }
            mongoBeanUtil.getJobInfoService().updateById(job);
            //检查是不是所有工作都删除了
            Long unCancel = mongoBeanUtil.getUserTempJobRecordService().lambdaQuery().eq(UserTempJobRecord::getJobId, job.getId()).eq(UserTempJobRecord::getUserId, UserContextManage.getContext().getId()).in(UserTempJobRecord::getApplyStatus, Arrays.asList(1, 3)).count();
            if (unCancel.equals(0)) {
                mongoBeanUtil.getJobApplyRecordService().update(new UpdateWrapper<JobApplyRecord>().eq(JobApplyRecord::getJobId, job.getId()).eq(JobApplyRecord::getUserId, UserContextManage.getContext().getId()).set(JobApplyRecord::getApplyStatus, 4));
            }
        }
        apply.setApplyStatus(4);
        apply.setConfirmTime(new Date());
        return mongoBeanUtil.getUserTempJobRecordService().updateById(apply);
    }


    @ApiOperation(response = UserJobBrowseRecord.class, value = "浏览记录", notes = "")
    @PostMapping(value = "/browseRecord")
    @UserLogAnnotation(title = "工作信息", action = "我的工作申请记录")
    public Object browseRecord(@RequestBody BaseSearchPageDTO dto) {
        PageParam page = new PageParam(dto.getPage(), dto.getSize());
        LambdaQueryChainWrapper queryWrapper = mongoBeanUtil.getUserJobBrowseRecordService().lambdaQuery();
        if (StringUtils.isNotBlank(dto.getOrder()) && StringUtils.isNotBlank(dto.getSort())) {
            if (dto.getSort().equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(dto.getOrder());
            } else {
                queryWrapper.orderByDesc(dto.getOrder());
            }
        } else {
            queryWrapper.orderByDesc("oper_time");
        }
        return mongoBeanUtil.getUserJobBrowseRecordService().page(queryWrapper, page);
    }

    @ApiOperation(response = JobApplyVO.class, value = "我的工作申请记录", notes = "")
    @PostMapping(value = "/applyRecord")
    @UserLogAnnotation(title = "工作信息", action = "我的工作申请记录")
    public Object applyRecord(@RequestBody QueryJobApplyDTO dto) {
        PageParam page = new PageParam(dto.getPage(), dto.getSize());
        LambdaQueryChainWrapper queryWrapper = mongoBeanUtil.getJobInfoService().lambdaQuery();
        if (StringUtils.isNotBlank(dto.getOrder()) && StringUtils.isNotBlank(dto.getSort())) {
            if (dto.getSort().equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(dto.getOrder());
            } else {
                queryWrapper.orderByDesc(dto.getOrder());
            }
        } else {
            queryWrapper.orderByDesc("apply_time");
        }
        queryWrapper.ne("job_type", 1);
        queryWrapper.ne("apply_status", 4);
        queryWrapper.eq("user_id", UserContextManage.getContext().getId());
        queryWrapper.eq(dto.getApplyStatus() != null, "apply_status", dto.getApplyStatus());
        PageResult<JobApplyRecord> pageInfo = mongoBeanUtil.getJobApplyRecordService().page(queryWrapper, page);
        PageResult<JobApplyVO> pageResult = new PageResult<>();
        CachedBeanCopier.copyObject(pageInfo, pageResult);
        if (!pageInfo.getContentData().isEmpty()) {
            List<String> jobIds = pageInfo.getContentData().stream().map(JobApplyRecord::getJobId).collect(Collectors.toList());
            List<JobInfo> jobs = mongoBeanUtil.getJobInfoService().getByIds(jobIds);
            List<String> companyIds = jobs.stream().map(JobInfo::getCompanyId).collect(Collectors.toList());
            List<CompanyInfo> companyInfos = companyIds == null || companyIds.isEmpty() ? new ArrayList<>() : mongoBeanUtil.getCompanyInfoService().getByIds(companyIds);
            List<JobApplyVO> list = new ArrayList<>();
            for (JobApplyRecord contentDatum : pageInfo.getContentData()) {
                JobApplyVO applyVO = new JobApplyVO();
                JobInfo job = jobs.stream().filter(i -> i.getId().equals(contentDatum.getJobId())).findFirst().orElse(null);
                CachedBeanCopier.copyObject(job, applyVO);
                applyVO.setWorkOnTime(DateUtilsEx.getStringHDateTime(job.getWorkOnTime()));
                applyVO.setWorkOffTime(DateUtilsEx.getStringHDateTime(job.getWorkOffTime()));
                applyVO.setDeadline(DateUtilsEx.getDay(job.getDeadline()));
                CachedBeanCopier.copyObject(contentDatum, applyVO);
                applyVO.setApplyTime(DateUtilsEx.getStringDateTime(contentDatum.getApplyTime()));
                applyVO.setContactTime(DateUtilsEx.getStringDateTime(contentDatum.getContactTime()));
                applyVO.setCheckTime(DateUtilsEx.getStringDateTime(contentDatum.getCheckTime()));
                applyVO.setConfirmTime(DateUtilsEx.getStringDateTime(contentDatum.getConfirmTime()));
                CompanyInfo companyInfo = companyInfos.stream().filter(i -> i.getId().equals(job.getCompanyId())).findFirst().orElse(null);
                applyVO.setCompanyInfo(companyInfo);
                list.add(applyVO);
            }
            pageResult.setContentData(list);
        }
        return pageResult;
    }


//    @ApiOperation(response = JobApplyVO.class, value = "零工工作申请记录", notes = "")
//    @PostMapping(value = "/tempApplyRecord")
//    @UserLogAnnotation(title = "工作信息", action = "零工工作申请记录")
//    public Object tempApplyRecord(@RequestBody QueryJobApplyDTO dto) {
//        PageParam page = new PageParam(dto.getPage(), dto.getSize());
//        LambdaQueryChainWrapper queryWrapper = mongoBeanUtil.getJobInfoService().lambdaQuery();
//        if (StringUtils.isNotBlank(dto.getOrder()) && StringUtils.isNotBlank(dto.getSort())) {
//            if (dto.getSort().equalsIgnoreCase("asc")) {
//                queryWrapper.orderByAsc(dto.getOrder());
//            } else {
//                queryWrapper.orderByDesc(dto.getOrder());
//            }
//        } else {
//            queryWrapper.orderByAsc("work_date");
//        }
////        queryWrapper.eq("job_type", 1);
//        queryWrapper.eq("user_id", UserContextManage.getContext().getId());
//        queryWrapper.eq(dto.getApplyStatus() != null, "apply_status", dto.getApplyStatus());
//        PageResult<UserTempJobRecord> pageInfo = mongoBeanUtil.getUserTempJobRecordService().page(queryWrapper, page);
//        PageResult<TempJobApplyVO> pageResult = new PageResult<>();
//        CachedBeanCopier.copyObject(pageInfo, pageResult);
//        if (!pageInfo.getContentData().isEmpty()) {
//            List<String> jobIds = pageInfo.getContentData().stream().map(UserTempJobRecord::getJobId).collect(Collectors.toList());
//            List<JobInfo> jobs = mongoBeanUtil.getJobInfoService().getByIds(jobIds);
//            List<String> companyIds = jobs.stream().map(JobInfo::getCompanyId).collect(Collectors.toList());
//            List<CompanyInfo> companyInfos = companyIds == null || companyIds.isEmpty() ? new ArrayList<>() : mongoBeanUtil.getCompanyInfoService().getByIds(companyIds);
//            List<TempJobApplyVO> list = new ArrayList<>();
//            for (UserTempJobRecord contentDatum : pageInfo.getContentData()) {
//                TempJobApplyVO applyVO = new TempJobApplyVO();
//                JobInfo job = jobs.stream().filter(i -> i.getId().equals(contentDatum.getJobId())).findFirst().orElse(null);
//                CompanyInfo companyInfo = companyInfos.stream().filter(i -> i.getId().equals(job.getCompanyId())).findFirst().orElse(null);
//                CachedBeanCopier.copyObject(job, applyVO);
//                applyVO.setSalary(job.getTempJobInfo().getSalary());
//                applyVO.setSalaryUnit(job.getTempJobInfo().getSalaryUnit());
//                applyVO.setWorkOnTime(DateUtilsEx.getStringHDateTime(job.getWorkOnTime()));
//                applyVO.setWorkOffTime(DateUtilsEx.getStringHDateTime(job.getWorkOffTime()));
//                CachedBeanCopier.copyObject(contentDatum, applyVO);
//                applyVO.setApplyTime(DateUtilsEx.getStringDateTime(contentDatum.getApplyTime()));
//                applyVO.setConfirmTime(DateUtilsEx.getStringDateTime(contentDatum.getConfirmTime()));
//                applyVO.setCompanyInfo(companyInfo);
//                list.add(applyVO);
//            }
//            pageResult.setContentData(list);
//        }
//        return pageResult;
//    }


    @ApiOperation(response = JobApplyVO.class, value = "零工工作申请记录", notes = "")
    @PostMapping(value = "/tempApplyRecord")
    @UserLogAnnotation(title = "工作信息", action = "零工工作申请记录")
    public Object tempApplyRecord(@RequestBody QueryJobApplyDTO dto) {
        PageParam page = new PageParam(dto.getPage(), dto.getSize());
        LambdaQueryChainWrapper queryWrapper = mongoBeanUtil.getJobInfoService().lambdaQuery();
        if (StringUtils.isNotBlank(dto.getOrder()) && StringUtils.isNotBlank(dto.getSort())) {
            if (dto.getSort().equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(dto.getOrder());
            } else {
                queryWrapper.orderByDesc(dto.getOrder());
            }
        } else {
            queryWrapper.orderByDesc("apply_time");
        }
        queryWrapper.eq("job_type", 1);
        queryWrapper.ne("apply_status", 4);
        queryWrapper.eq("user_id", UserContextManage.getContext().getId());
        queryWrapper.eq(dto.getApplyStatus() != null, "apply_status", dto.getApplyStatus());
        PageResult<JobApplyRecord> pageInfo = mongoBeanUtil.getJobApplyRecordService().page(queryWrapper, page);
        PageResult<JobApplyVO> pageResult = new PageResult<>();
        CachedBeanCopier.copyObject(pageInfo, pageResult);
        if (!pageInfo.getContentData().isEmpty()) {
            List<String> jobIds = pageInfo.getContentData().stream().map(JobApplyRecord::getJobId).collect(Collectors.toList());
            List<JobInfo> jobs = mongoBeanUtil.getJobInfoService().getByIds(jobIds);
            List<UserTempJobRecord> tempRecords = mongoBeanUtil.getUserTempJobRecordService().lambdaQuery().in(UserTempJobRecord::getJobId, jobIds).eq(UserTempJobRecord::getUserId, UserContextManage.getContext().getId())
                    .ne(UserTempJobRecord::getApplyStatus, 4).list();
            List<UserTempJobRecord> tempWorkList = tempRecords.stream().sorted(Comparator.comparing(UserTempJobRecord::getWorkDate)).collect(Collectors.toList());
            List<String> companyIds = jobs.stream().map(JobInfo::getCompanyId).collect(Collectors.toList());
            List<CompanyInfo> companyInfos = companyIds == null || companyIds.isEmpty() ? new ArrayList<>() : mongoBeanUtil.getCompanyInfoService().getByIds(companyIds);
            List<JobApplyVO> list = new ArrayList<>();
            for (JobApplyRecord contentDatum : pageInfo.getContentData()) {
                JobApplyVO applyVO = new JobApplyVO();
                JobInfo job = jobs.stream().filter(i -> i.getId().equals(contentDatum.getJobId())).findFirst().orElse(null);
                CachedBeanCopier.copyObject(job, applyVO);
                applyVO.setWorkOnTime(DateUtilsEx.getStringHDateTime(job.getWorkOnTime()));
                applyVO.setWorkOffTime(DateUtilsEx.getStringHDateTime(job.getWorkOffTime()));
                applyVO.setDeadline(DateUtilsEx.getDay(job.getDeadline()));
                CachedBeanCopier.copyObject(contentDatum, applyVO);
                applyVO.setApplyTime(DateUtilsEx.getStringDateTime(contentDatum.getApplyTime()));
                applyVO.setContactTime(DateUtilsEx.getStringDateTime(contentDatum.getContactTime()));
                applyVO.setCheckTime(DateUtilsEx.getStringDateTime(contentDatum.getCheckTime()));
                applyVO.setConfirmTime(DateUtilsEx.getStringDateTime(contentDatum.getConfirmTime()));
                List<UserTempJobRecord> tempList = tempWorkList.stream().filter(i -> i.getJobId().equals(contentDatum.getJobId())).collect(Collectors.toList());
                List<TempJobApplyedVO> workDayHireList = new ArrayList<>();
                CompanyInfo companyInfo = companyInfos.stream().filter(i -> i.getId().equals(job.getCompanyId())).findFirst().orElse(null);
                applyVO.setCompanyInfo(companyInfo);
                for (UserTempJobRecord userTempJobRecord : tempList) {
                    TempJobApplyedVO tempApplyVO = new TempJobApplyedVO();
                    tempApplyVO.setId(userTempJobRecord.getId());
                    tempApplyVO.setWorkDate(userTempJobRecord.getWorkDate());
                    tempApplyVO.setApplyStatus(userTempJobRecord.getApplyStatus());
                    tempApplyVO.setSalary(job.getTempJobInfo().getSalary());
                    tempApplyVO.setSalaryUnit(job.getTempJobInfo().getSalaryUnit());
                    tempApplyVO.setWorkOnTime(DateUtilsEx.getStringHDateTime(job.getWorkOnTime()));
                    tempApplyVO.setWorkOffTime(DateUtilsEx.getStringHDateTime(job.getWorkOffTime()));
                    tempApplyVO.setApplyTime(DateUtilsEx.getStringDateTime(contentDatum.getApplyTime()));
                    tempApplyVO.setConfirmTime(DateUtilsEx.getStringDateTime(contentDatum.getConfirmTime()));
                    workDayHireList.add(tempApplyVO);
                }
                applyVO.setWorkDayHireList(workDayHireList);
                list.add(applyVO);
            }
            pageResult.setContentData(list);
        }
        return pageResult;
    }


    @ApiOperation(response = JobListVO.class, value = "工作列表", notes = "")
    @PostMapping(value = "/jobList")
    @Transactional
    @UserLogAnnotation(title = "工作信息", action = "工作列表")
    @UserPassportSSO(ignore = true, needInfo = true)
    public Object jobList(@RequestBody JobListDTO dto) {
        PageParam page = new PageParam(dto.getPage(), dto.getSize());
        LambdaQueryChainWrapper queryWrapper = mongoBeanUtil.getJobInfoService().lambdaQuery();
        if (StringUtils.isNotBlank(dto.getOrder()) && StringUtils.isNotBlank(dto.getSort())) {
            if (dto.getSort().equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(dto.getOrder());
            } else {
                queryWrapper.orderByDesc(dto.getOrder());
            }
        } else {
            queryWrapper.orderByDesc("_id");
        }
        queryWrapper.eq("job_status", 1).eq("audit_status", 1);
        queryWrapper.eq(dto.getJobType() != null, "job_type", dto.getJobType());
        queryWrapper.eq(dto.getJobCategory() != null, "job_category", dto.getJobCategory());
        queryWrapper.eq(dto.getSettlementType() != null, "settlement_type", dto.getSettlementType());
        queryWrapper.eq(dto.getPublishNature() != null, "publish_nature", dto.getPublishNature());
        queryWrapper.like(StringUtils.isNoneBlank(dto.getJobTitle()), "job_title", dto.getJobTitle());
        queryWrapper.like(StringUtils.isNoneBlank(dto.getJobAddress()), "job_address", dto.getJobAddress());
        if (StringUtils.isNotBlank(dto.getCompanyName())) {
            List<String> companyIds = mongoBeanUtil.getCompanyInfoService().lambdaQuery().like(CompanyInfo::getCompanyName, dto.getCompanyName()).list().stream().map(CompanyInfo::getId).collect(Collectors.toList());
            if (companyIds == null || companyIds.isEmpty()) {
                return page;
            }
            queryWrapper.in("company_id", companyIds);
        }
        PageResult<JobInfo> pageInfo = mongoBeanUtil.getJobInfoService().page(queryWrapper, page);
        PageResult<JobListVO> pageresult = new PageResult<JobListVO>();
        if (pageInfo.getContentData() != null && !pageInfo.getContentData().isEmpty()) {
            CachedBeanCopier.copyObject(pageInfo, pageresult);
            List<String> companyIds = pageInfo.getContentData().stream().map(JobInfo::getCompanyId).collect(Collectors.toList());
            List<String> jobIds = pageInfo.getContentData().stream().map(JobInfo::getId).collect(Collectors.toList());
            List<CompanyInfo> companyInfos = companyIds == null || companyIds.isEmpty() ? new ArrayList<>() : mongoBeanUtil.getCompanyInfoService().getByIds(companyIds);
            List<JobApplyRecord> applyRecords = new ArrayList<>();
            if (UserContextManage.getContext() != null) {
                applyRecords = mongoBeanUtil.getJobApplyRecordService().lambdaQuery().eq(JobApplyRecord::getUserId, UserContextManage.getContext().getId()).in(JobApplyRecord::getJobId, jobIds).list();
            }
            List<JobListVO> jobListVOS = new ArrayList<>();
            for (JobInfo contentDatum : pageInfo.getContentData()) {
                JobListVO jobListVO = new JobListVO();
                CachedBeanCopier.copyObject(contentDatum, jobListVO);
                if (StringUtils.isNotBlank(contentDatum.getCompanyId())) {
                    CompanyInfo company = companyInfos.stream().filter(i -> i.getId().equals(contentDatum.getCompanyId())).findFirst().orElse(null);
                    jobListVO.setCompanyInfo(company);
                }
                if (StringUtils.isNotBlank(contentDatum.getJobCategory())) {
                    JobCategory category = mongoBeanUtil.getJobCategoryService().getById(contentDatum.getJobCategory());
                    jobListVO.setJobCategoryName(category.getCategoryName());
                }
                JobApplyRecord apply = applyRecords.stream().filter(i -> i.getJobId().equals(contentDatum.getId())).findFirst().orElse(null);
                jobListVO.setApplyStaus(apply == null ? 0 : apply.getApplyStatus());
                jobListVO.setWorkOnTime(DateUtilsEx.getStringHDateTime(contentDatum.getWorkOnTime()));
                jobListVO.setWorkOffTime(DateUtilsEx.getStringHDateTime(contentDatum.getWorkOffTime()));
                jobListVO.setDeadline(DateUtilsEx.getDay(contentDatum.getDeadline()));
                jobListVOS.add(jobListVO);
            }
            pageresult.setContentData(jobListVOS);
        }
        return pageresult;
    }


}
